/**
 * Creat with IntelliJ IDEA
 * Description:Runnable接口
 * User:WZW
 * Date:2021-11-26
 * Time:21:15
 */
class TargetObject implements Runnable
{
    private int number = 0;//全局变量（在同一目标对象的不同线程之间共享）
    public void setNumber(int n)
    {
        number = n;
    }
    public void run()
    {
        while(true)
        {
            if(Thread.currentThread().getName().equals("add"))//当现在是add在跑时
            {
                number++;
                System.out.printf("%d\n",number);
            }
            if(Thread.currentThread().getName().equals("sub"))//当现在是sub在跑时
            {
                number--;
                System.out.printf("%12d\n",number);
            }
            try{ Thread.sleep(1000); }//中断1秒
            catch(InterruptedException e) {}
        }
    }
}

public class Example8_5 {
    public static void main(String args[])
    {
        TargetObject a1 = new TargetObject();
        a1.setNumber(10);
        TargetObject a2 = new TargetObject();
        a2.setNumber(-10);

        Thread threadA,threadB,threadC,threadD;
        threadA = new Thread(a1); // 目标对象a1
        threadB = new Thread(a1); // 目标对象a1
        threadA.setName("add");
        threadB.setName("add");
        threadC = new Thread(a2); // 目标对象a2
        threadD = new Thread(a2); // 目标对象a2
        threadC.setName("sub");
        threadD.setName("sub");
        threadA.start();
        threadB.start();
        threadC.start();
        threadD.start();
    }
}

